/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   14-8-4 上午11:08 Created by dwzhang
 */
package com.jade.framework.mom;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 抽象的消息队列生产者。
 *
 * @author dwzhang
 * @version 1.0 14-8-4 上午11:08
 */
public abstract class AbstractProducer implements MomProducer
{
    protected Log log = LogFactory.getLog(this.getClass());
    protected boolean start = false;

    @PostConstruct
    public void init()
    {
        doInit();
    }

    @PreDestroy
    public void destroy()
    {
        if (isStarted()) {
            stop();
        }
        doDestroy();
    }


    public boolean isStarted()
    {
        return start;
    }

    public boolean isStopped()
    {
        return !start;
    }

    public void start()
    {
        if (isStarted()) {
            log.warn("Mom producer has already been started!");
            return;
        }

        try {
            log.info("Start mom producer...");
            doStart();
            start = true;
            log.info("Start mom producer...Done");
        }
        catch (Throwable t) {
            log.warn("Can't start producer:", t);
        }
    }

    public void stop()
    {
        if (isStopped()) {
            log.warn("Mom producer has already been stopped!");
            return;
        }

        try {
            log.info("Stop mom producer...");
            doStop();
            start = false;
            log.info("Stop mom producer...Done");
        }
        catch (Throwable t) {
            log.warn("Can't stop producer:", t);
        }
    }

    protected abstract void doInit();

    protected abstract void doDestroy();

    protected abstract void doStart()
            throws Exception;

    protected abstract void doStop()
            throws Exception;

    public MomSendResult send(String topic, String key, String tag, int delayLevel, Object msg)
            throws MomException
    {
        MomMessage message = new MomMessage();
        message.setTopic(topic);
        message.setKey(key);
        message.setTag(tag);
        message.setMsg(msg);
        message.setDelayLevel(delayLevel);
        return send(message);
    }
}
